import axios from 'axios'
import Vue from 'vue'
import { getToken } from '@/utils/auth' // get token from cookie
axios.defaults.timeout = 100000     // 响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json'  // 配置请求头
  //配置接口地址
axios.defaults.baseURL = 'http://andi.56matrix.com' ;

// POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
  const token = getToken()||''
console.log(token);
  if (token) {
        config.headers['token'] = token;
        const item = sessionStorage.getItem('item')
        if(item){
          config.headers['Content-Type'] = 'multipart/form-data'  
        }
  }
  return config
}, (error) => {
  console.log('错误的传参', 'fail')
  return Promise.reject(error)
})

axios.interceptors.response.use((res) => {
  if(res.status === 200) {
    return res;
  } else {
    Vue.prototype.$message.error(res.data.msg);
  }
  return Promise.reject(res);
}, (error) => {
  // 网络异常
  return Promise.reject({message: '网络异常，请刷新重试', err: error});
});


//返回一个Promise(发送post请求)
export function fetch(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(response => {
      resolve(response.data);
    }).catch((error) => {
      reject(error);
    });
  });
}


//返回一个Promise(发送post请求)
export function fetchdelete(url, params) {
  return new Promise((resolve, reject) => {
    axios.delete(url, params).then(response => {
      resolve(response.data);
    }).catch((error) => {
      reject(error);
    });
  });
}

export function fetchget(url, params = {}) {
  const suffix = Object.keys(params).map(name => {
    return `${name}=${params[name]}`;
  }).join('&');
  const urls = `${url}?${suffix}`;
  return new Promise((resolve, reject) => {
     axios.get(urls, params).then(response => {
          resolve(response.data);
    }).catch((error) => {
        reject(error)
    })
  })
}


export function fetchput(url, params) {
  return new Promise((resolve, reject) => {
    axios.put(url, params).then(response => {
      resolve(response.data);
    }).catch((error) => {
      reject(error)
    })
  })
}
